import { Component, OnInit, OnDestroy, Input, SimpleChanges, OnChanges } from '@angular/core';
import { DataSourceService } from '../../../../service/data-source/data-source.service';
import { DeviceChannel } from '../../../../entity/device-channel.model';
import { OverlayPanel } from 'primeng/primeng';
import { ConvergenceBox } from '../convergencebox';
import { Http } from '@angular/http';
import { DatePipe } from '@angular/common';
import { List } from 'linqts';
import { ApplicationService } from '../../../../service/application.service';
import { DeviceService } from '../../../../service/device.service';
import { DeviceChannelService } from '../../../../service/device-channel.service';
import { Tag } from '../../../../entity/tag.model';
import { Farm } from '../../../../entity/farm.model';
import { Device } from '../../../../entity/device.model';
import { InterceptorService } from '../../../../service/interceptor/interceptor-service';

@Component({
  selector: 'app-convergencebox-view',
  templateUrl: './convergencebox-view.component.html',
  styleUrls: ['./convergencebox-view.component.css']
})
export class ConvergenceboxViewComponent implements OnInit, OnDestroy, OnChanges {

  @Input() farm: Farm = null;
  @Input() device: Device = null;
  @Input() inverters: Device[] = null;

  public convergenceBoxs: ConvergenceBox[] = [];
  public channelMaxCount: number = 0;
  public channelTitles: string[] = [];
  public currentConvergenceBox: ConvergenceBox = null;

  private innerConvergenceBoxs: ConvergenceBox[] = [];
  private dataSource: DataSourceService;
  public showDetail: boolean;
  constructor(
    private http: InterceptorService,
    private datePipe: DatePipe,
    private application: ApplicationService,
    private deviceService: DeviceService,
    private deviceChannelService: DeviceChannelService, ) { }

  ngOnInit() {
  }
  ngOnDestroy(): void {
    if (this.dataSource != null) {
      this.dataSource.dispose();
    }
  }
  ngOnChanges(changes: SimpleChanges): void {
    if (changes['farm'] != null && changes['farm'].currentValue != null) {
      this.loadConvergenceboxByFarm(this.farm);
    }
    if (changes['device'] != null && changes['device'].currentValue != null) {
      this.loadConvergenceboxByDevice(this.device);
    }
    if (changes['inverters'] != null && changes['inverters'].currentValue != null) {
      this.getDispalyConvergenceBoxs(this.innerConvergenceBoxs);
    }
  }
  /**
   * 双击
   * @param {ConvergenceBox} convergenceBox
   * @memberof ConvergenceboxListComponent
   */
  onDblClick(event, convergenceBox: ConvergenceBox, overlaypanel: OverlayPanel) {
    this.currentConvergenceBox = convergenceBox;
    this.showDetail = true;

  }
  /**
   * 点击关闭
   *
   * @memberof ConvergenceboxViewComponent
   */
  onColse() {
    this.showDetail = false;
  }
  /**
   *
   *
   * @private
   * @param {Farm} farm
   * @memberof ConvergenceboxViewComponent
   */
  private loadConvergenceboxByFarm(farm: Farm) {
    const convergenceBoxsGet = this.deviceService.getConvergenceBoxsByFarmId(farm.farmId);
    const channelsGet = this.deviceChannelService.getDeviceChannelsByFarmId(farm.farmId);
    this.commondLoadConvergencebox(convergenceBoxsGet, channelsGet);
  }
  /**
   *
   *
   * @private
   * @param {Device} device
   * @memberof ConvergenceboxViewComponent
   */
  private loadConvergenceboxByDevice(device: Device) {
    const convergenceBoxsGet = this.deviceService.getDeviceByParentId(device.deviceId);
    const channelsGet = this.deviceChannelService.getDeviceChannelsByParentId(device.deviceId);
    this.commondLoadConvergencebox(convergenceBoxsGet, channelsGet);
  }
  private commondLoadConvergencebox(convergenceBoxsGet: Promise<Device[]>, channelsGet: Promise<DeviceChannel[]>) {
    if (this.dataSource != null) {
      this.dataSource.dispose();
    }
    const voltage = this.application.tagDict['tvol'];
    this.dataSource = new DataSourceService(this.http, this.datePipe);
    this.channelTitles = [];
    this.convergenceBoxs = [];
    this.innerConvergenceBoxs = [];
    this.channelMaxCount = 0;
    Promise.all([convergenceBoxsGet, channelsGet])
      .then(res => {
        const devices = res[0] ? res[0] : [];
        const deviceChannels = res[1] ? res[1] : [];
        devices.forEach(device => {
          const convergenceBox: ConvergenceBox = {
            deviceId: device.deviceId,
            deviceName: device.subArrayName + device.deviceName,
            parentId: device.parentId,
            deviceCode: device.deviceCode,
            farmId: device.farmId,
            farmName: device.farmName,
            farmCode: device.farmCode,
            subArrayId: device.subArrayId,
            subArrayName: device.subArrayName,
            modelId: device.modelId,
            voltage: this.dataSource.binding([device.farmCode, device.deviceCode], voltage),
            channels: [],
            dispaly: true
          };
          // 查询汇流箱的电流支路
          let channels = deviceChannels.filter(channel => channel.deviceId === device.deviceId);
          if (channels != null && channels.length > 0) {
            channels = new List<DeviceChannel>(channels).OrderBy(channel => channel.seq).ToArray()
            // 确定电流支路最大基数
            this.channelMaxCount = this.channelMaxCount < channels.length ? channels.length : this.channelMaxCount;
            channels.forEach(channel => {
              if (channel.channelEnabled) {
                const tag = this.application.tagDict[channel.channelTagKey];
                if (tag !== null) {
                  convergenceBox.channels.push(this.dataSource.binding([device.farmCode, device.deviceCode], tag));
                }
              } else {
                convergenceBox.channels.push(null);
              }
            });
          }
          this.innerConvergenceBoxs.push(convergenceBox);
        });
        // 以最大电流支路条数为基数为每个汇流箱建立相同的电流支路数
        this.innerConvergenceBoxs.forEach(convergenceboxs => {
          const count = this.channelMaxCount - convergenceboxs.channels.length;
          if (count > 0) {
            for (let i = 0; i < count; i++) {
              convergenceboxs.channels.push(null);
            }
          }
        });
        for (let i = 0; i < this.channelMaxCount; i++) {
          this.channelTitles.push(`支路${i + 1}`);
        };
        this.getDispalyConvergenceBoxs(this.innerConvergenceBoxs);
        this.dataSource.begin();
      })
      .catch(err => {
        console.log(err);
      });
  }
  private getDispalyConvergenceBoxs(innerConvergenceBoxs: ConvergenceBox[]) {
    this.convergenceBoxs = [];
    if (this.inverters != null && this.inverters.length > 0) {
      innerConvergenceBoxs.forEach(convergenceBox => {
        if (convergenceBox.parentId != 0) {
          if (this.inverters.findIndex(inverter => inverter.deviceId === convergenceBox.parentId) != -1) {
            this.convergenceBoxs.push(convergenceBox);
          }
        }
      });
    } else {
      this.convergenceBoxs = this.innerConvergenceBoxs;
    }

  }
}



// WEBPACK FOOTER //
// ./src/app/module/monitor/convergencebox-list/convergencebox-view/convergencebox-view.component.ts